﻿using LogisticsTrackingWebApi_V2.Services;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;

namespace LogisticsTrackingWebApi_V2.Controllers
{

    [ApiController]
    [Route("api/[controller]")]
    public class LogisticsController : ControllerBase
    {
        private readonly ILogisticsService _logisticsService;
        private readonly ILogger<LogisticsController> _logger;

        public LogisticsController(ILogisticsService logisticsService, ILogger<LogisticsController> logger)
        {
            _logisticsService = logisticsService;
            _logger = logger;
        }

        /// <summary>
        /// 获取所有支持的物流公司
        /// </summary>
        /// <returns>物流公司列表</returns>
        [HttpGet("companies")]
        public IActionResult GetSupportedCompanies()
        {
            var companies = _logisticsService.GetSupportedCompanies()
                .Select(c => new { Code = c.Code, Name = c.Name });

            return Ok(companies);
        }

        /// <summary>
        /// 查询物流信息
        /// </summary>
        /// <param name="trackingNumber">物流单号</param>
        /// <param name="companyCode">公司代码（可选）</param>
        /// <returns>物流信息</returns>
        [HttpGet]
        public async Task<IActionResult> QueryLogistics(
            [FromQuery, Required] string trackingNumber,
            [FromQuery] string? companyCode = null)
        {
            try
            {
                var result = await _logisticsService.QueryLogisticsAsync(trackingNumber, companyCode);
                return Ok(result);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (KeyNotFoundException ex)
            {
                return NotFound(ex.Message);
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询物流信息时发生错误");
                return StatusCode(500, "查询物流信息时发生错误，请稍后重试");
            }
        }
    }

}
